package com.example.statemachine.support;

import com.example.statemachine.support.annotation.StateMachine;
import com.example.statemachine.support.annotation.StateTransition;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.stereotype.Component;
import org.springframework.util.ReflectionUtils;

import java.lang.reflect.Method;

@Slf4j
@Component
public class StateMachineBeanPostProcessor implements BeanPostProcessor {

    private final StateTransitionProcessor stateTransitionProcessor;

    // 使用构造函数注入，避免循环依赖
    public StateMachineBeanPostProcessor(StateTransitionProcessor stateTransitionProcessor) {
        this.stateTransitionProcessor = stateTransitionProcessor;
        log.info("StateMachineBeanPostProcessor 初始化完成");
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        Class<?> beanClass = bean.getClass();

        // 检查类是否被@StateMachine注解标记
        StateMachine stateMachineAnnotation = AnnotationUtils.findAnnotation(beanClass, StateMachine.class);
        if (stateMachineAnnotation != null) {
            log.info("发现状态机Bean: {} (entityType: {})",
                    beanClass.getSimpleName(), stateMachineAnnotation.entityType().getSimpleName());

            // 扫描所有方法，查找@StateTransition注解
            Method[] methods = ReflectionUtils.getAllDeclaredMethods(beanClass);
            for (Method method : methods) {
                StateTransition transitionAnnotation = AnnotationUtils.findAnnotation(method, StateTransition.class);
                if (transitionAnnotation != null) {
                    // 注册状态转换方法
                    stateTransitionProcessor.registerTransitionMethod(beanClass, method, transitionAnnotation);
                }
            }
        }
        return bean;
    }
}